<template>
	<div class="login-wrap">
		<div class="ms-login">
			<div class="ms-title">智能灯光调控系统</div>
			<el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
				<el-form-item prop="username">
					<el-input v-model="param.loginAccount" placeholder="username">
						<template #prepend>
							<el-button :icon="User"></el-button>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input>
						type="password"
						placeholder="password"
						v-model="param.password"
						@keyup.enter="submitForm(login)"
					>
						<template #prepend>
							<el-button :icon="Lock"></el-button>
						</template>
					</el-input>
				</el-form-item>
				<div class="login-btn">
					<el-button type="primary" @click="submitForm(login)">登录</el-button>
				</div>
				<p class="login-tips">Tips : 用户名和密码随便填。</p>
			</el-form>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useTagsStore } from '../store/tags';
import { usePermissStore } from '../store/permiss';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Lock, User } from '@element-plus/icons-vue';
import API from '../utils/axios';

interface LoginInfo {
	loginAccount: string;
	password: string;
}

const router = useRouter();
const param = reactive<LoginInfo>({
	loginAccount: 'admin',
	password: '123123'
});
// 表单验证
const rules: FormRules = {
	loginAccount: [
		{
			required: true,
			message: '请输入用户名',
			trigger: 'blur'
		}
	],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const permiss = usePermissStore();
const login = ref<FormInstance>();
const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			ElMessage.success('登录成功');
			// 发送登录信息
			const loginData = {
				loginAccount:'',
				loginIp:'',
			}
			// 创建异步函数来获取公网IP
			const getPublicIP = () => new Promise<void>((resolve, reject) => {
				fetch('https://api.ipify.org?format=json')
						.then(response => response.json())
						.then(data => {
							const ipAddress = data.ip;
							loginData.loginIp = ipAddress;
							resolve();
						})
						.catch(error => {
							console.error('Error fetching IP address: ', error);
							reject(error);
						});
			});

			// 创建异步函数来存储用户登录数据
			const storeLoginData = () => new Promise<void>((resolve, reject) => {
				loginData.loginAccount = param.loginAccount;
				API.post('/LogFile/insertLogLogin', loginData)
						.then((res) => {
							console.log(res.data);
							localStorage.setItem('login_time', res.data.data.loginTime);
							localStorage.setItem('login_ip', res.data.data.loginIp);
							localStorage.setItem('ip_type', res.data.data.ipType);
							// 登录用户信息存储与授权
							localStorage.setItem('ms_username', res.data.data.loginName);
							localStorage.setItem('ms_role', res.data.data.loginRole);
							const keys = permiss.defaultList[localStorage.getItem('ms_role') == 'admin' ? 'admin' : 'user'];
							permiss.handleSet(keys);
							localStorage.setItem('ms_keys', JSON.stringify(keys));
							resolve();
						})
						.catch((err) => reject(err));
			});

			// Async函数来依次执行获取公网IP和存储数据的操作
			(async () => {
				try {
					await getPublicIP();
					await storeLoginData();
					router.push('/');
				} catch (error) {
					console.error(error);
				}
			})();
		} else {
			ElMessage.error('登录失败');
			return false;
		}
	});
};

const tags = useTagsStore();
tags.clearTags();
</script>

<style scoped>
.login-wrap {
	position: relative;
	width: 100%;
	height: 100%;
	background-image: url(../assets/img/login-bg.jpg);
	background-size: 100%;
}
.ms-title {
	width: 100%;
	line-height: 50px;
	text-align: center;
	font-size: 20px;
	color: #fff;
	border-bottom: 1px solid #ddd;
}
.ms-login {
	position: absolute;
	left: 50%;
	top: 50%;
	width: 350px;
	margin: -190px 0 0 -175px;
	border-radius: 5px;
	background: rgba(255, 255, 255, 0.3);
	overflow: hidden;
}
.ms-content {
	padding: 30px 30px;
}
.login-btn {
	text-align: center;
}
.login-btn button {
	width: 100%;
	height: 36px;
	margin-bottom: 10px;
}
.login-tips {
	font-size: 12px;
	line-height: 30px;
	color: #fff;
}
</style>
